#include "VideoOutput.h"

VideoOutput::VideoOutput(AVFrameQueue* frame_queue, const int video_width, const int video_height)
    : frame_queue_(frame_queue), video_width_(video_width), video_height_(video_height),
      window_(nullptr), renderer_(nullptr), texture_(nullptr), yuv_buffer_(nullptr) {
}

int VideoOutput::Init() {
    // 初始化SDL
    if (!SDL_Init(SDL_INIT_VIDEO)) {
        av_log(nullptr, AV_LOG_ERROR, "SDL_Init failed: %s\n", SDL_GetError());
        return -1;
    }

    // 创建窗口 (SDL3 API)
    window_ = SDL_CreateWindow("视频播放器", video_width_, video_height_, SDL_WINDOW_RESIZABLE);
    if (!window_) {
        av_log(nullptr, AV_LOG_ERROR, "SDL_CreateWindow failed: %s\n", SDL_GetError());
        return -1;
    }

    // 创建渲染器
    renderer_ = SDL_CreateRenderer(window_, nullptr);
    if (!renderer_) {
        av_log(nullptr, AV_LOG_ERROR, "SDL_CreateRenderer failed: %s\n", SDL_GetError());
        return -1;
    }

    // 创建纹理 (YUV420格式)
    texture_ = SDL_CreateTexture(renderer_,
                               SDL_PIXELFORMAT_IYUV,
                               SDL_TEXTUREACCESS_STREAMING,
                               video_width_,
                               video_height_);
    if (!texture_) {
        av_log(nullptr, AV_LOG_ERROR, "SDL_CreateTexture failed: %s\n", SDL_GetError());
        return -1;
    }

    // 初始化矩形区域
    rect_.x = 0;
    rect_.y = 0;
    rect_.w = video_width_;
    rect_.h = video_height_;

    // 不需要YUV缓冲区，直接使用AVFrame数据
    yuv_buffer_ = nullptr;
    yuv_buffer_size_ = 0;

    return 0;
}

int VideoOutput::MainLoop() {
    SDL_Event event;
    bool running = true;
    uint64_t last_frame_time = SDL_GetTicks();
    const uint64_t frame_delay = 1000 / 60; // 目标帧率60FPS

    while (running) {
        uint64_t start_time = SDL_GetTicks();

        // 处理事件
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
                case SDL_EVENT_KEY_DOWN:
                    if (event.key.key == SDL_SCANCODE_ESCAPE) {
                        av_log(nullptr, AV_LOG_INFO, "ESC key pressed\n");
                        running = false;
                    }
                    break;
                case SDL_EVENT_QUIT:
                    running = false;
                    break;
                default:
                    break;
            }
        }

        // 刷新视频
        double remaining_time = 0.0;
        VideoRefresh(&remaining_time);

        // 精确帧率控制
        uint64_t frame_time = SDL_GetTicks() - start_time;
        if (frame_time < frame_delay) {
            SDL_Delay(frame_delay - frame_time);
        }
    }

    return 0;
}

void VideoOutput::VideoRefresh(double* remaining_time) {
    if (frame_queue_->Size() <= 0) {
        return;
    }

    AVFrame* frame = frame_queue_->Front();
    if (!frame) {
        return;
    }

    // 更新纹理
    SDL_UpdateYUVTexture(texture_, &rect_,
                        frame->data[0], frame->linesize[0],
                        frame->data[1], frame->linesize[1],
                        frame->data[2], frame->linesize[2]);

    // 渲染
    SDL_RenderClear(renderer_);
    SDL_RenderTexture(renderer_, texture_, nullptr, nullptr);
    SDL_RenderPresent(renderer_);

    // 释放帧
    frame_queue_->Pop(1);
    av_frame_free(&frame);
}

VideoOutput::~VideoOutput() {
    if (texture_) {
        SDL_DestroyTexture(texture_);
        texture_ = nullptr;
    }
    if (renderer_) {
        SDL_DestroyRenderer(renderer_);
        renderer_ = nullptr;
    }
    if (window_) {
        SDL_DestroyWindow(window_);
        window_ = nullptr;
    }
    if (yuv_buffer_) {
        free(yuv_buffer_);
        yuv_buffer_ = nullptr;
    }
    SDL_Quit();
}